<?php

namespace App\Http\Controllers\api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Game;
use App\UserGame;

class GameController extends Controller
{


    // 删除活动
    public function del($gameId){

        $game = Game::find($gameId);
        $res = $game->delete();
        return response()->json(["code"=>200,"msg"=>"删除成功","res"=>$res]);

    }

    // 参与活动
    public function join($gameId){

        $user = \Auth::guard("api")->user();
        $user->games()->attach($gameId);

        return response()->json(["status"=>200,"msg"=>"报名成功"]);

    }

    // 获取活动列表
    public function list(){

        //$games = Game::all();
        $games = Game::withCount(["users"])->get();

        foreach ($games as $k=>$game){
            $games[$k]["type_name"] = $game->type->name;
            if($game->user->icon){
                $games[$k]["user_icon"] = config('app.upload').$game->user->icon;
            }else{
                $games[$k]["user_icon"] = false;
            }
            
            $games[$k]["user_name"] = $game->user->name;
            $games[$k]["venue_name"] = $game->venue->name;
        }

        return $games;
    }
      
      // 获取活动列表
      public function detail(Request $request ){

        //$user = \Auth::guard('api')->user();
        $user_id = \Auth::id();

        //$games = Game::all();
        $game = Game::withCount(["users"])->find($request->id);

        if($game['users_count'] >= $game['number']){
            $game['is_full'] = true;
        }else{
            $game['is_full'] = false;
        }

        $game["type_name"] = $game->type->name;
        $game["user_icon"] =  config('app.upload').$game->user->icon;
        $game["user_name"] = $game->user->name;
        $game["venue_name"] = $game->venue->name;
        $game['is_join'] = $this->is_join($user_id,$request->id);
        return response()->json(['status'=>200,'msg'=>'获取成功!','data'=>$game]);
       
    }

    // 是否参与
    private  function is_join($user_id,$game_id){
        return (bool) UserGame::where('user_id',$user_id)
        ->where("game_id",$game_id)
        ->first();
    }


    //保存活动
    public function save(Request $request){
        //保存活动

        $user = \Auth::guard("api")->user();
        $game = new Game();
        $game->title = $request->title;
        $game->user_id = $user->id;
        $game->type_id = $request->type_id;
        $game->type_id = $request->type_id;
        $game->venue_id = $request->venue_id;
        $game->datetime = $request->datetime;
        $game->number = $request->number;

        $res = $game->save();

        return response()->json(["code"=>200,"msg"=>"活动创建成功","game"=>$res]);

    }

}
